package com.anstudio.busfetion;

import java.util.Vector;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.anstudio.busfetion.R;
import com.anstudio.busfetion.model.FavoriteItem;
import com.anstudio.busfetion.util.LocalUtil;
import com.anstudio.busfetion.util.NetworkUtil;
import com.feedback.UMFeedbackService;
import com.mobclick.android.MobclickAgent;
/**
 *
 * @author zsb
 *  The main activity for this application provide the bus-station-search service to user.
 */
public class MainActivity extends Activity implements View.OnClickListener{
	private static final int FAV_REQUEST_CODE = 0x000001;
	private static final int Setting_REQUEST_CODE = 0x000001;
    private EditText mStationEdit;
    private EditText mLineNoEdit;
    private TextView mSearchResult;
    private View mProgress;
    private Button mSearchButton;
    private LocalUtil mLocalUtil = null;
    //private String splitString = BusFetionConfig.DELIMITER;
    private String line_no = "";
    private String station = "";

    public static void launch(Activity activity){
        Intent intent = new Intent(activity, MainActivity.class);
        activity.startActivity(intent);
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        MobclickAgent.onError(this);
        setContentView(R.layout.service_layout);
        mLocalUtil = new LocalUtil();
        FavoriteItem item = getFavoriteItemFromUtil();
        mStationEdit = (EditText) findViewById(R.id.station_edit);
        mStationEdit.setText(item.getStation());
        mLineNoEdit = (EditText) findViewById(R.id.line_no_edit);
        mLineNoEdit.setText(item.getBus());
        mSearchResult = (TextView) findViewById(R.id.result_edit);
        mProgress = findViewById(R.id.loading);
        mSearchButton = (Button) findViewById(R.id.search_result_button);

        mSearchButton.setOnClickListener(this);

        checkNetwrokTask.execute();
    }

    private FavoriteItem getFavoriteItemFromUtil(){
    	String[] strings = mLocalUtil.localLoadFav();
    	FavoriteItem item = null;
    	if(strings.length>0){
    	    item = new FavoriteItem();
    	    item.setBus(strings[strings.length-2]);
    	    item.setStation(strings[strings.length-1]);
    	}
    	return item;
    }

    /**
     * Be called when the search begin to request.
     */
    private void showProgress(){
        if(mProgress==null){
            mProgress = findViewById(R.id.loading);
        }
        clearResult();
        mProgress.setVisibility(View.VISIBLE);
    }

    /**
     * Be called when the search request end.
     */
    private void stopProgress(){
        if(mProgress==null){
            mProgress = findViewById(R.id.loading);
        }
        mProgress.setVisibility(View.GONE);
    }

    /**
     * Clear the content of mSearchResult
     */
    private void clearResult(){
        mSearchResult.setText(R.string.clear_content);
    }

    /**
     * Be called when the Search button is clicked.
     * This method will judge whether the values of line_no and station are right,
     * and will start a AsyncTask to get the information from server.
     */
    private void submit(final boolean isFuzzy){
        line_no = mLineNoEdit.getText().toString();
        station = mStationEdit.getText().toString();
        /**
         * Get information for bus from server in async.
         */
        AsyncTask<Void, Void, Integer> requestTask = new AsyncTask<Void, Void, Integer>(){

            NetworkUtil parser = new NetworkUtil();
            @Override
            protected void onPostExecute(Integer result) {
                // TODO Auto-generated method stub
                stopProgress();
                Vector<String> resultContent = parser.getRequestBusInfo();
                switch(result){
                case BusFetionConfig.BUS_FETION_SELECT_SITE:
                    String[] temp = {};
                    final String[] strings = resultContent.toArray(temp);
                    new AlertDialog.Builder(MainActivity.this)
                    .setTitle(R.string.select_site)
                    .setItems(strings, new DialogInterface.OnClickListener(){

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // TODO Auto-generated method stub
                            mStationEdit.setText(strings[which]);
                            submit(false);
                        }

                    })
                    .show();
                    break;
                case BusFetionConfig.BUS_FETION_SUCCESS:
                	mLocalUtil.localSaveFav(line_no, station);
                case BusFetionConfig.BUS_FETION_NO_SITE:
                case BusFetionConfig.BUS_FETION_FAILED:
                case BusFetionConfig.BUS_FETION_IGNORED:
                    String searchResult = "";
                    if(result!=null){
//                        String[] subStrings = result.split(splitString);
                        for(String content: resultContent){
                            if(content!=null&&!"null".equals(content))
                                searchResult = searchResult+content+"\n";
                        }
                    }
                    mSearchResult.setText(searchResult);
                    break;
                default:break;
                }


            }

            @Override
            protected void onPreExecute() {
                // TODO Auto-generated method stub
                super.onPreExecute();
                showProgress();
            }

            @Override
            protected Integer doInBackground(Void... params) {
                // TODO Auto-generated method stub
                int number = parser.requestBusInfo(line_no, station, isFuzzy);
                return number;
            }

        };
        if(line_no.equals("")||station.equals("")){
            new AlertDialog.Builder(MainActivity.this)
                .setTitle(R.string.tip_title)
                .setMessage(R.string.error_message)
                .setPositiveButton(R.string.ok, null)
                .show();
        }else{
            requestTask.execute();
        }
    }


    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch(v.getId()){
        case R.id.search_result_button:

            submit(true);
            break;
        default:break;
        }
    }

    /**
     * Check whether the network is available.
     */
    AsyncTask<Void, Void, Boolean> checkNetwrokTask = new AsyncTask<Void, Void, Boolean>(){

        @Override
        protected Boolean doInBackground(Void... params) {
            // TODO Auto-generated method stub
            NetworkUtil parser = new NetworkUtil();
            return parser.checkNetwork();
        }

        @Override
        protected void onPostExecute(Boolean result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            if(!result){
                Toast.makeText(MainActivity.this, R.string.network_tip, Toast.LENGTH_LONG).show();
            }
        }
    };

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    // TODO Auto-generated method stub
    MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_menu, menu);
    return true;
  }
  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    // TODO Auto-generated method stub
     switch (item.getItemId()) {
     case R.id.feedback:
    	 UMFeedbackService.openUmengFeedbackSDK(this);
    	 break;
     case R.id.favorite:
    	 FavoriteActivity.launchForResult(this, FAV_REQUEST_CODE);
    	 break;
     case R.id.setting:
    	 SettingActivity.launch(this);
    	 break;
     }
    return true;
  }
  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	// TODO Auto-generated method stub
	super.onActivityResult(requestCode, resultCode, data);
	switch(requestCode){
	case FAV_REQUEST_CODE:
		if(resultCode==RESULT_OK){
			FavoriteItem item = new FavoriteItem();
			item.setBus(data.getStringExtra("bus"));
			item.setStation(data.getStringExtra("station"));
			updateUI(item);
		}
		break;
	}
  }
  
  private void updateUI(FavoriteItem item){
	  mLineNoEdit.setText(item.getBus());
	  mStationEdit.setText(item.getStation());
  }

}
